<template>
    <div class="container" v-if="isLoggedIn">
      <h2>个人中心</h2>
      <div class="card" style="width: 18rem;">
        <img :src="userAvatar" class="card-img-top" alt="User Avatar" />
        <div class="card-body">
          <h5 class="card-title">{{ user.name }}</h5>
          <div v-if="!isEditing">
            <p class="card-text">{{ user.bio }}</p>
          </div>
          <div v-else>
            <textarea v-model="editableBio" class="form-control"></textarea>
          </div>
          <div class="my1">
            <a href="#" class="btn btn-primary" @click="toggleEdit">{{ editBtnCaption }}</a>
          </div>
          
        </div>
      </div>
    </div>
</template>
  
<script setup>
import { computed, ref } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import apiConfig from '@/config';

const store = useStore();
const router = useRouter();
const isLoggedIn = computed(() => store.state.isLoggedIn);

const userAvatar = new URL('@/assets/labubu2.jpg', import.meta.url).href;
const editBtnCaption = computed(() => isEditing.value ? '保存' : '编辑');
const user = computed(() => store.state.user);
// 管理是否处于编辑状态
const isEditing = ref(false);
// 可编辑的 bio 数据
const editableBio = ref(user.value.bio);
const toggleEdit = () => {
  if(isEditing.value){
    saveChanges();
  }else{
    isEditing.value = true;
  }
};
const saveChanges = async () => {
  try {
    // 更新本地状态
    const updatedUser = { ...user.value, bio: editableBio.value };
    store.commit('updateUser', updatedUser); // Vuex 中 updateUsers 提交方法

    // 调用 API 异步更新数据库
    await fetch(`${apiConfig}/users/${user.value.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
      },
      body: JSON.stringify(updatedUser)
    });

    // 退出编辑状态
    isEditing.value = false;
  } catch (error) {
    console.error('保存失败:', error);
  }
};
if (!isLoggedIn.value) {
  router.push('/login'); // 如果未登录，跳转到登录页面
}
</script>
<style scoped>
.my1 {
  margin-top: 1rem;
}
</style>